tool
extends EditorPlugin

const CommitDialog = preload("CommitDialog.tscn")

var _gd_editor_node : GDEditorNode
var _terminal = _GitUtil_Terminal.new()
var _commit_dialog = CommitDialog.instance()
var _menu = MenuButton.new()
var _menu_id = {
	"Pull": 0,
	"Commit": 0,
	"Push": 1,
	"CommitAndPush": 2,
}


func _enter_tree():
	call_deferred("init_data")


func _exit_tree():
	if _menu:
		_menu.queue_free()
	if _commit_dialog:
		_commit_dialog.queue_free()


func init_data():
	_gd_editor_node = GDEditorNode.new()
	
	_commit_dialog.connect("commit", self, "_commit")
	get_editor_interface().get_editor_viewport().add_child(_commit_dialog)
	
	_menu.switch_on_hover = true
	_menu.text = "Git"
	_gd_editor_node.editor_menu_container.add_child(_menu)
	
	# 菜单
	var popup = _menu.get_popup()
	for m in _menu_id.keys():
		popup.add_item(m.capitalize())
	
	popup.connect("id_pressed", self, "_id_pressed")


func _id_pressed(id):
	printt(_menu_id.CommitAndPush, id)
	match id:
		_menu_id.Push:
			trans_to(PUSH)
			yield(_terminal.push(), "completed")
			trans_to(FINISH)
		
		_menu_id.Pull:
			trans_to(PULL)
			yield(_terminal.pull(), "completed")
			trans_to(FINISH)
		
		_menu_id.Commit:
			_commit_and_push = false
			_commit_dialog.popup_centered()
		
		_menu_id.CommitAndPush:
			_commit_and_push = true
			_commit_dialog.popup_centered()
	


var _commit_and_push : bool = false
func _commit(desc: String):
	if desc.strip_edges() == "":
		var datetime = OS.get_datetime()
		desc = "%02d/%02d/%02d %02d:%02d:%02d 时提交" % [
			datetime['year'], datetime['month'], datetime['day'], 
			datetime['hour'], datetime['minute'], datetime['second'], 
		]
	trans_to(COMMINT)
	yield(_terminal.commit(desc), "completed")
	if _commit_and_push:
		yield(_terminal.push(), "completed")
	trans_to(FINISH)


enum {
	FINISH = 0,
	COMMINT,
	PUSH,
	PULL,
}

func trans_to(state):
	match state:
		FINISH:
			_menu.disabled = false
		COMMINT, PUSH, PULL:
			_menu.disabled = true


